﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class RecentlyStarDir : MonoBehaviour {
	
	public GameObject hero;//玩家
	public Sprite showSprite;//显示游标的图片
	public Sprite alphaSprite;//隐藏游标的图片
	

	private Collider2D[] colliderArr;//所有collider集合
	private List<GameObject> starArr;//星球集合
	private float[] starDistances;//星球距离集合
	private float minDistance;//
	private int whichTarget;//
	private GameObject targetStar;//目标星球
	private Vector3 dir;//游标应该指向的方向
	private float distance = 25f;//隐藏游标的距离

	// Use this for initialization
	void Start () {
		starArr = new List<GameObject>();
	}
	
	// Update is called once per framet
	void Update () {
        FindTarget();
	}

	private void FindTarget()
	{
		if(hero != null)
		{
			// 得到碰撞器
			colliderArr = Physics2D.OverlapCircleAll(hero.transform.position, 1000, 1 << LayerMask.NameToLayer("Enemy"));
			// 过滤得到所有星球
			if(colliderArr.Length != 0 && hero != null)
			{
				for (int i = 0; i < colliderArr.Length; i++)
				{
					if(colliderArr[i].gameObject.tag == "Enemy"&&colliderArr[i].gameObject.GetComponent<Star>().state!=Star.state_death)
					{
						starArr.Add(colliderArr[i].gameObject);
					}
				}
				if (starArr.Count == 0) {
                    //Debug.Log ("已经消灭所有星球");
                    //星球已经全部消灭
                    GameManager.instance.starClear = true;
					return; 
				}
				// 得到距离集合
				starDistances = new float[starArr.Count];
				for (int i = 0; i < starDistances.Length; i++)
				{
					starDistances[i] = Vector3.Distance(hero.transform.position, starArr[i].transform.position);
				}
				// 得到最近距离
				minDistance = starDistances[0];
				for (int i = 0; i < starDistances.Length; i++)
				{
					if(starDistances[i] <= minDistance)
					{
						minDistance = starDistances[i];
						whichTarget = i;
					}
				}

				// 设置目标转方向
				targetStar = starArr[whichTarget];
				dir = (targetStar.transform.position - hero.transform.position).normalized;
				dir.z = 0;
				transform.right = dir;
				starArr.Clear();
				//UGUI设置图片的方式
				if ((targetStar.transform.position - hero.transform.position).magnitude < distance) 
				{
					gameObject.GetComponent<Image>().overrideSprite = alphaSprite;
				} else 
				{
					gameObject.GetComponent<Image>().overrideSprite = showSprite;
				}
			}
			else
			{
				gameObject.GetComponent<Image>().overrideSprite = alphaSprite;
			}
		}
		

		
	}
}
